use std::process::Command;

#[test]
fn test_tree_basic_functionality() {
    let output = Command::new("cargo")
        .args(&["run", "--", "--help"])
        .output()
        .expect("Failed to execute tree command");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("类似树状结构的目录和文件列表显示工具"));
    assert!(stdout.contains("--all"));
    assert!(stdout.contains("--dirs-only"));
    assert!(stdout.contains("--level"));
}

#[test]
fn test_tree_src_directory() {
    let output = Command::new("cargo")
        .args(&["run", "--", "src"])
        .output()
        .expect("Failed to execute tree command");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("src"));
    assert!(stdout.contains("main.rs"));
}

#[test]
fn test_tree_dirs_only() {
    let output = Command::new("cargo")
        .args(&["run", "--", "-d", "."])
        .output()
        .expect("Failed to execute tree command");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    // Should show directories but the file count should be 0
    assert!(stdout.contains("0 个文件"));
}

#[test]
fn test_tree_level_limit() {
    let output = Command::new("cargo")
        .args(&["run", "--", "-L", "1", "."])
        .output()
        .expect("Failed to execute tree command");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    // Should limit depth to 1 level
    assert!(stdout.contains("个目录"));
}

#[test]
fn test_tree_show_size() {
    let output = Command::new("cargo")
        .args(&["run", "--", "-s", "src"])
        .output()
        .expect("Failed to execute tree command");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    // Should show file sizes in brackets
    assert!(stdout.contains("KB") || stdout.contains("B"));
    assert!(stdout.contains("[") && stdout.contains("]"));
}

#[test]
fn test_tree_output_to_file() {
    use std::fs;
    use std::path::Path;
    
    let test_output_file = "test_output.txt";
    
    // Clean up any existing test file
    let _ = fs::remove_file(test_output_file);
    
    let output = Command::new("cargo")
        .args(&["run", "--", "-o", test_output_file, "src"])
        .output()
        .expect("Failed to execute tree command");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("树状结构已输出到文件"));
    
    // Verify the file was created and contains expected content
    assert!(Path::new(test_output_file).exists());
    let file_content = fs::read_to_string(test_output_file)
        .expect("Failed to read output file");
    assert!(file_content.contains("src"));
    assert!(file_content.contains("main.rs"));
    
    // Clean up
    let _ = fs::remove_file(test_output_file);
}